<?php
// read data from a file
function test_fread() {
    $file = 'log.txt';
    $fh = fopen($file, 'r');
    $data = fread($fh, filesize($file));
    fclose($fh);

    echo $data;
}

// write data to a file
function test_fwrite($data) {
    $file = 'log.txt';
    $fh = fopen($file, 'w') or die("can't open file");
    fwrite($fh, $data);
    fclose($fh);
}

// read lines from a file
function test_file() {
    $file = 'log.txt';
    $lines = file($file);

    foreach ($lines as $line) {
        echo($line);
    }
}

// Using file() for reading large text files > 10 Mb gives problems, therefore you should use this instead.
// It is much slower but it works fine. $lines will return an array with all the lines.
// read lines from a file, better performance
function test_fgets() {
    $file = 'log.txt';
    $fh = fopen($file, 'r');
    while (!feof($fh)) {
        $buffer = fgets($fh, 4096); // max length of a line is 4096
        $lines[] = $buffer;
    }

    fclose($fh);
}



$file = 'log.txt';

function config_log_request() {
    //if (!user_is_authenticated()) return;
    $user = 'rogerxu';
    global $file;

    $allowed_users = file($file);
    if (!in_array($user."\n", $allowed_users)) {
        die("对不起，您不是受邀用户，无法登录。");
    } else {
        die("Hello, $user");
    }
}


if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    $today = getdate();

    header('Content-Type: text/html; charset=utf-8');
    header('Cache-Control: private, no-cache');

    if (!isset($_GET['u'])) {
        config_log_request();
        exit;
    }

    $user = strtolower($_GET['u']);
    $data = $user."\n";
    file_put_contents($file, $data);

    print_r($today);
} else {
    $data = file_get_contents('php://input');
    file_put_contents($file, $data);
    header('Content-Type: application/octet-stream');
    header('Cache-Control: private, no-cache');
    echo '';
}
?>

<p>
  <textarea cols="100" rows="20"><?php echo file_get_contents($file); ?></textarea>
</p>
